package net.celisdelafuente.java.Acacia.entity;

import java.sql.SQLException;
import java.util.ArrayList;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName="authors")
public class Author {
	
	public static final String ID_FIELD_NAME = "id";
	public static final String NAME_FIELD_NAME = "name";
	public static final String LNAME_FIELD_NAME = "lname";
	public static final String MNAME_FIELD_NAME = "mname";
	
	@DatabaseField(columnName = ID_FIELD_NAME, generatedId = true)
	private int id;
	
	@DatabaseField(columnName = NAME_FIELD_NAME, canBeNull = false)
	private String name;
	
	@DatabaseField(columnName=LNAME_FIELD_NAME, canBeNull=false)
	private String lname;
	
	@DatabaseField(columnName=MNAME_FIELD_NAME, canBeNull=true)
	private String mname;
	
	public Author() {} // Mandatory empty constructor
	
	public Author(String[] fullName) {
		if(fullName.length > 1) {
			this.name = fullName[0];
			this.lname = fullName[1];
			if(fullName.length < 2)
				this.mname = fullName[2];
		}
	}
	
	public Author(String name, String lname, String mname) {
		this.name = name;
		this.lname = lname;
		this.mname = mname;
	}
	
	public Author(String name, String lname) {
		this.name = name;
		this.lname = lname;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLname() {
		return lname;
	}

	public void setLname(String lname) {
		this.lname = lname;
	}

	public String getMname() {
		return mname;
	}

	public void setMname(String mname) {
		this.mname = mname;
	}
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	public Author getByFullName(ConnectionSource conn, 
			Dao<Author, Integer> dao,
			String[] fullName) {
		Author a = this;
		ArrayList<Author> author = new ArrayList<Author>();
		QueryBuilder<Author, Integer> qb = dao.queryBuilder();
		Where<Author, Integer> where = qb.where();
		try {
			if(fullName.length < 3) {
				where.and(where.eq(Author.NAME_FIELD_NAME, fullName[0]),
						where.eq(Author.LNAME_FIELD_NAME, fullName[1]));
			} else if (fullName.length == 3) {
				where.and(where.eq(Author.NAME_FIELD_NAME, fullName[0]),
						where.eq(Author.LNAME_FIELD_NAME, fullName[1]),
						where.eq(Author.MNAME_FIELD_NAME, fullName[2]));
			} else {
				return a;
			}
			qb.limit(1);
			PreparedQuery<Author> pq = qb.prepare();
			author = (ArrayList<Author>)dao.query(pq);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(!author.isEmpty())
			a = (Author) author.get(0);
		return a;
	}
}
